package pub.cleangao.memm.transport.socket;

import pub.cleangao.memm.exception.RpcException;
import pub.cleangao.memm.registry.RpcRuntime;
import pub.cleangao.memm.registry.RpcServiceRegistry;
import pub.cleangao.memm.transport.RequestTransport;
import pub.cleangao.memm.transport.message.RpcRequest;
import pub.cleangao.memm.transport.message.RpcResponse;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class SocketRpcClient implements RequestTransport {


    private final RpcServiceRegistry serviceRegistry;

    public SocketRpcClient() {
        serviceRegistry = RpcRuntime.getRegistry();
    }


    @Override
    @SuppressWarnings("unchecked")
    public RpcResponse<Object> send(RpcRequest rpcRequest) {
        InetSocketAddress inetSocketAddress = serviceRegistry.lookupService(rpcRequest);
        try (Socket socket = new Socket()) {
            socket.connect(inetSocketAddress);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeObject(rpcRequest);
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            return (RpcResponse<Object>) objectInputStream.readObject();
        } catch (Exception e) {
            throw new RpcException(e);
        }
    }

    @Override
    public void shutdown() {

    }


}
